package com.yzz.composeweatherproject.http.okhttp

import android.webkit.WebSettings
import com.yzz.composeweatherproject.IDataSuccessListener
import com.yzz.composeweatherproject.MyApplication
import com.yzz.composeweatherproject.entity.LocationBean
import com.yzz.composeweatherproject.entity.WeatherDetailedBean
import com.yzz.composeweatherproject.http.DomainNameUtils
import com.yzz.composeweatherproject.http.jsoup.JsoupUtils
import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit


class OkHttpUtils private constructor() {

    val mOkHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder().addInterceptor {
            val request = it.request().newBuilder()
                .removeHeader("User-Agent")
                .addHeader(
                    "User-Agent",
                    WebSettings.getDefaultUserAgent(MyApplication.getInstance())
                )
                .build()
            it.proceed(request)
        }.connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build()
    }


    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder = OkHttpUtils()
    }

    private fun handleOkhttpEnqueue(string: String, responseCallback: Callback) {
        mOkHttpClient.newCall(Request.Builder().url(string).build()).enqueue(responseCallback)
    }

    fun getWeatherUrl(string: String?, listener: IDataSuccessListener<WeatherDetailedBean>?) {
        if (string == null) {
            return
        }
        val urlstr = DomainNameUtils.weatherUrl + string
        handleOkhttpEnqueue(urlstr, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                listener?.onFail(e.message)
            }

            override fun onResponse(call: Call, response: Response) {
                val data = response.body?.string()
                listener?.onSuccess(JsoupUtils.getWeatherDetailedData(data))
            }

        })
    }

    fun getLocationUrl(listener: IDataSuccessListener<LocationBean>) {
        handleOkhttpEnqueue(DomainNameUtils.weatherPeUrl, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                listener.onFail(e.message)
            }

            override fun onResponse(call: Call, response: Response) {
                val data = response.body?.string()
                if (data != null) {
                    listener.onSuccess(JsoupUtils.getLocationData(data))
                } else {
                    listener.onFail("")
                }
            }
        })

    }

}